package com.shiku.im.room.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.shiku.im.comm.utils.StringUtil;
import com.shiku.im.repository.MongoRepository;
import com.shiku.im.room.entity.RoomChanceSettings;
import com.shiku.im.room.service.RoomChanceSettingsService;
import com.shiku.im.user.dao.UserChanceSettingsService;
import com.shiku.im.user.dao.impl.UserChanceSettingsServiceImpl;
import com.shiku.im.user.entity.UserChanceSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Repository
public class RoomChanceSettingsServiceImpl extends MongoRepository<RoomChanceSettings, String> implements RoomChanceSettingsService {

    @Autowired
    private UserChanceSettingsServiceImpl userChanceSettingsService;

    @Override
    public Class<RoomChanceSettings> getEntityClass() {
        return RoomChanceSettings.class;
    }

    @Override
    public RoomChanceSettings getSettingsByJid(String jid) {
        RoomChanceSettings settings = findOne("_id", jid);
        if(settings == null){
            settings = new RoomChanceSettings();
        }
        UserChanceSettings defaultSettings = getDefaultSettings();
        if(StringUtil.isEmpty(settings.getSettings())){
            settings.setSettings(defaultSettings.getSettings());
        }
        if(StringUtil.isEmpty(settings.getBigSettings())){
            settings.setBigSettings(defaultSettings.getBigSettings());
        }
        if(settings.getBigStart() == null){
            settings.setBigStart(defaultSettings.getBigStart());
        }
        return settings;
    }
    @Override
    public UserChanceSettings getDefaultSettings() {
        return userChanceSettingsService.getDefaultSettings();
    }
    @Override
    public void addOrUpdateSettings(String jid, String str, Float bigStart, String bigStr) {
        RoomChanceSettings settings = findOne("_id", jid);
        if(settings == null){
            settings = new RoomChanceSettings();
            settings.setJid(jid);
        }
        if(!StringUtil.isEmpty(str)){
            settings.setSettings(str);
        }
        if(bigStart != null){
            settings.setBigStart(bigStart);
        }
        if(!StringUtil.isEmpty(bigStr)){
            settings.setBigSettings(bigStr);
        }
        save(settings);
    }
    @Override
    public void addOrUpdateSettingsToAll(String str, Float bigStart, String bigStr) {
        Update update = createUpdate();
        if(!StringUtil.isEmpty(str)){
            update.set("settings", str);
        }
        if(bigStart != null){
            update.set("bigStart", bigStart);
        }
        if(!StringUtil.isEmpty(bigStr)){
            update.set("bigSettings", bigStr);
        }
        update(new Query(), update);
    }
    @Override
    public RoomChanceSettings init(String jid) {
        RoomChanceSettings settings = new RoomChanceSettings();
        settings.setJid(jid);
        JSONObject jsonObject = new JSONObject();
        for (int i = 5; i < 11; i++) {
            for (int j = 0; j < i; j++) {
                jsonObject.put(i + "-" + (j + 1), getReallyProbability(i, j + 1));
            }
        }
        settings.setSettings(jsonObject.toJSONString());
        save(settings);
        return settings;
    }

    private double getReallyProbability(int packetCount, int bombCount) {
        BigInteger n = new BigInteger(String.valueOf(packetCount));
        BigInteger l = new BigInteger(String.valueOf(bombCount));
        BigInteger nine = new BigInteger("9");

        double v = factorial(n).multiply(factorial(n.add(nine).subtract(l))).doubleValue() / (factorial(n.add(nine)).multiply(factorial(n.subtract(l)))).doubleValue();
        BigDecimal bigDecimal = new BigDecimal(v);
        BigDecimal result = bigDecimal.setScale(8, BigDecimal.ROUND_HALF_UP);
        return result.doubleValue();
    }

    private BigInteger factorial(BigInteger number) {
        BigInteger one = new BigInteger("1");
        if (number.compareTo(one) < 1)
            return one;
        else
            return number.multiply(factorial(number.subtract(one)));
    }

    private int[] getNums(String title) {
        StringBuilder builder = new StringBuilder("[");
        String pattern = "[^0-9]";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(title);
        while (m.find()) {
            String s = m.group();
            if (s.equals("\\")) {
                s = "\\\\";
            }
            builder.append(s);
        }
        builder.append("]");
        if (!builder.toString().equals("[]")) {
            String[] haveMoney = title.split(builder.toString());
            if (haveMoney.length == 2) {
                title = haveMoney[1];
            }
        }

        int[] nums;
        if (title.equals("财源滚滚，心想事成") || title.equals("恭喜发财,万事如意")) {
            nums = new int[1];
            nums[0] = 1;
        } else {
            try {
                nums = new int[title.length()];
                String[] split = title.split("");
                for (int i = 0; i < split.length; i++) {
                    String s = split[i];
                    nums[i] = Integer.parseInt(s);
                }
            } catch (NumberFormatException e) {
//                nums = getHaveMoneyNums(title);
//                if (title== null) {
//                    return null;
//                }
                return null;
            }
        }
        //去重
        HashSet<Integer> list = new HashSet<>();
        for (int num : nums) {
            list.add(num);
        }
        int[] newNums = new int[list.size()];
        int i = 0;
        for (Integer integer : list) {
            newNums[i] = integer;
            i++;
        }
        return newNums;
    }

}
